package com.zhanyd.app;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;

public class Test3 {

	public static void main(String[] args) {
		
		 System.out.println((byte)0x81);
		 //byte转二进制
		 System.out.println(Integer.toBinaryString(((byte)-125 & 0xFF) + 0x100).substring(1));
		/*//读线圈
		byte[] sendData = getSendByteRead((byte)1,0,1);
		operateModbus(sendData);
		//写单个线圈
		sendData = getSendByteWriteSigle((byte)5,0,(byte)0xFF,(byte)0x00);
		operateModbus(sendData);
		//读线圈
		sendData = getSendByteRead((byte)1,0,1);
		operateModbus(sendData);*/
		
		
		/*//写多个线圈
		byte[] sendData = getSendByteWriteMultiCoils((byte)15,0,10,(byte)2,(byte)0xff,(byte)0xff);
		byte[] sendData = new byte[]{
				0x00,0x01,0x00,0x00,0x00,0x09,0x01,0x0F,0x00,0x00,0x00,0x0A,0x02,(byte) 0xCD,0x01
		};
		operateModbus(sendData);
		//读线圈
		sendData = getSendByteRead((byte)1,0,10);
		operateModbus(sendData);*/
		
		/*//读寄存器
		byte[] sendData = getSendByteRead((byte)3,0,1);
		operateModbus(sendData);
		//写单个寄存器
		sendData = getSendByteWriteSigle((byte)6,0,(byte)0x01,(byte)0x11);
		operateModbus(sendData);
		//读线圈
		sendData = getSendByteRead((byte)3,0,1);
		operateModbus(sendData);*/
		
		//读寄存器
		/*byte[] sendData = getSendByteRead((byte)3,9,2);
		byte[] dataArray = operateModbus(sendData);
		System.out.println();
		System.out.println(byteToIntBigEndian(dataArray));
		System.out.println(Float.intBitsToFloat(byteToIntBigEndian(dataArray)));*/
		
		Float f= 190.1f;
		System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
		byte[] numData = hexToBytes(Integer.toHexString(Float.floatToIntBits(f)));
		System.out.println("转换后的字节数组：" + numData);
		//写多个寄存器
		//byte[] sendData = getSendByteWriteMultiCoils((byte)16,0,2,(byte)4,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff);
		byte[] sendData = new byte[]{
				0x00,0x01,0x00,0x00,0x00,0x0B,0x01,0x10,0x00,0x03,0x00,0x02,0x04,numData[0],numData[1],numData[2],numData[3]
		};
		operateModbus(sendData);
		//读寄存器
		sendData = getSendByteRead((byte)3,3,2);
		operateModbus(sendData);
	}
	
     /**
      * 读写操作	
      */
	 public static byte[] operateModbus(byte[] sendData) {

			int port = 502;
			String server = "localhost";
			Socket socket = null;
			
			OutputStream output = null;
			InputStream input = null;
			
			byte[] dataArray;
			
			// connect to server
			try {
			    socket = new Socket(server, port);
			    System.out.println("\nConnected with server " + socket.getInetAddress() + ":" + socket.getPort());
			
			  System.out.println("客户端发送: ");
			    for(byte item : sendData){
			    	System.out.print(item + " ");
			    }
			    output = socket.getOutputStream();
			    output.write(sendData);
			    //output.flush();
			    input = socket.getInputStream(); 
				byte[] returnArray = new byte[50];
			    input.read(returnArray , 0, 50);
			    //第9位是数据位的长度
			    int dataLength = returnArray[8];
			    dataArray = new byte[dataLength];
			    System.out.println("\n客户端接收: ");
			    for(byte item : returnArray){
			    	System.out.print(item + " ");
			    }
			    System.out.println("\n数据域: ");
			    int k = 0;
			    for(int i= 9; i < dataLength + 9; i++){
			    	System.out.print(returnArray[i] + " ");
			    	dataArray[k] = returnArray[i];
			    	k++;
			    }
			    return dataArray;
			}
			catch (IOException e) {
			    System.out.println(e);
			    return null;
			}
			finally{
				try {
					output.close();
					socket.close();
					input.close();
				}
				catch (IOException e) {
					System.out.println(e);
				}
			}
	}
	 
	/**
	 * 读数据
	 * @param function
	 * @param address
	 * @param count
	 * @return
	 */
	public static byte[] getSendByteRead(byte function,int address,int count) {
		return new byte[]{
			0x00, 0x01, 0x00, 0x00, 0x00, //tcp 的头, 默认不变
			0x06,     //字节长度
			0x01,     //默认服务器
			function, //功能号 0-5 读取为3
			(byte)(address >> 8), (byte)(address & 0x00ff), //起始地址
			(byte)(count >> 8), (byte)(count & 0x00ff)     //获取的word数量
		};
	}
	
	/**
	 * 写数据
	 * @param function
	 * @param address
	 * @param hight
	 * @param low
	 * @return
	 */
	public static byte[] getSendByteWriteSigle(byte function,int address,byte hight,byte low) {
		return new byte[]{
			0x00, 0x01, 0x00, 0x00, 0x00, //tcp 的头, 默认不变
			0x06,     //字节长度
			0x01,     //默认服务器
			function, //功能号 0-5 读取为3
			(byte)(address >> 8), (byte)(address & 0x00ff), //起始地址
			hight, low     //设置的值
		};
	}
	
	/**
	 * 写多个线圈
	 * @param function
	 * @param address
	 * @param hight
	 * @param low
	 * @return
	 */
	public static byte[] getSendByteWriteMultiCoils(byte function,int address,int writeCount,byte byteCount,byte hight,byte low) {
		return new byte[]{
			0x00, 0x01, 0x00, 0x00, 0x00, //tcp 的头, 默认不变
			0x09,     //字节长度
			0x01,     //默认服务器
			function, //功能号 0-5 读取为3
			(byte)(address >> 8), (byte)(address & 0x00ff), //起始地址
			(byte)(writeCount >> 8), (byte)(writeCount & 0x00ff), //输出数量
			byteCount, //字节数
			hight, low     //设置的值
		};
	}
	
	/**
	 * byte转int大头模式
	 * @param byteData
	 * @return
	 */
	public static int byteToIntBigEndian(byte[] byteData){
		return (
				(byteData[0] << 24) |
				((byteData[1] & 0xFF) << 16) |
				((byteData[2] & 0xFF) << 8) |
				((byteData[3] & 0xFF) )
				);
	}
	
	
	/**
     * 将16进制字符串转换为byte[]
     * 
     * @param str
     * @return
     */
    public static byte[] hexToBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }


}
